import { createApp, App } from 'vue';
import { Router } from 'vue-router';
import ElementPlus from 'element-plus';
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import FsscAdmin from '@fssc/admin'
import { createErrorHandle } from '@fssc/admin';
import { initStore } from '../store';
import type { InitStoreOption } from '../store';
import { initRouter } from '../router';
import type { InitRouterOption } from '../router';
import FsscApp from '../App.vue';
import type { FsscUtilOption } from './app-util';
import fsscAppUtil, { FsscAppUtil } from './app-util';
import { initRequest } from '../api/index'
import type { HttpRequestConfig } from '../api/index'

export type InitFsscAppOption = FsscUtilOption & Omit<InitRouterOption, 'fsscAppUtil'>  &  InitStoreOption & {
  onAppBeforeMounted?: (app: App) => void,
  requestConfig?: HttpRequestConfig,
}

export function createFsscApp(option: {
  fsscAppUtil?: FsscAppUtil,
  store: any,
  router: Router,
  onAppBeforeMounted?: (app: App) => void,
}): App {
  const app = createApp(FsscApp);

  app.use(ElementPlus, {
    locale: zhCn,
  });
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
    app.component(`ElIcon${component.name}`, component)
  }
  app.use(FsscAdmin as any);

  if (option.store) {
    app.use(option.store);
  }
  if(option.router) {
    app.use(option.router);
  }

  if (option.onAppBeforeMounted) {
    option.onAppBeforeMounted(app)
  }

  app.mount('#app');
  if (option.fsscAppUtil) {
    app.config.errorHandler = function(error){
      console.error(error)
      option.fsscAppUtil.checkMessageToRefresh(error)
    }
  }

  return app;
}

export function initFsscApp(option: InitFsscAppOption) {
  FsscAppUtil.checkPassportAuthRedirect()
  const env = option.env;

  initRequest({
    baseURL:  (env.DEV ? env.VITE_PROXY_PREFIX : '') + env.VITE_APP_API_BASEURL,
    errorHandle: createErrorHandle((err) => {
      fsscAppUtil.login(err);
    }),
    ...(option.requestConfig || {}),
  })
  fsscAppUtil.init(option);

  initStore(option)
  initRouter({
    fsscAppUtil,
    ...option,
  })
  const appConfig = {
    fsscAppUtil,
    router: option.router,
    store: option.store,
    onAppBeforeMounted: option.onAppBeforeMounted,
  }

  if (window.__POWERED_BY_WUJIE__) {
    let app: any;
    window.__WUJIE_MOUNT = () => {
      app = createFsscApp(appConfig);
    };
    window.__WUJIE_UNMOUNT = () => {
      app.unmount();
    };
    window.__WUJIE.mount()
  } else {
    createFsscApp(appConfig);
  }
}
